package com.nxy.cpfsfe.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by nxygyzd on 2019/11/27.
 */
public class HttpUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 主动发送报文至ngixn服务器|业务系统（xml）
     * @param nginxMsg
     * @param map
     */
    public static  void responseSendXml(String nginxMsg,Map map){
        responseSendXml(nginxMsg,null,map);
    }

    /**
     * 主动发送报文至ngixn服务器|业务系统（xml）
     * @param nginxMsg
     * @param busMsg
     * @param map
     */
    public static  void responseSendXml(String nginxMsg,String busMsg ,Map map){
        //定义http请求对象
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        //定义http Head头
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("MsgTp", StringUtil.trimObject(map.get("/root/MsgHeader/MsgTp")));
        requestHeaders.add("CorrId", StringUtil.trimObject(map.get("/root/MsgHeader/CorrId")));
        requestHeaders.add("SndBankId", StringUtil.trimObject(map.get("/root/MsgHeader/RcvBankId")));
        requestHeaders.add("RcvBankId", StringUtil.trimObject(map.get("/root/MsgHeader/SndBankId")));
        //定义请求数据信息
        String nginxUrl = StringUtil.trimObject(map.get("NginxUrl"));
        String busUrl = StringUtil.trimObject(map.get("/root/MsgHeader/ClbckUrl"));
        responseSend(nginxMsg,nginxUrl,busMsg,busUrl,requestHeaders);
    }

    /**
     * 主动发送报文至ngixn服务器|业务系统(Json)
     * @param nginxMsg
     * @param map
     */
    public static  void responseSendJson(String nginxMsg,Map map){
        responseSendJson(nginxMsg,null, map);
    }
    /**
     * 主动发送报文至ngixn服务器|业务系统(Json)
     * @param nginxMsg
     * @param busMsg
     * @param map
     */
    public static  void responseSendJson(String nginxMsg,String busMsg,Map map){
        //定义http Head头
        Map<String ,Object> nginxMap = new HashMap<String,Object >();
        Map<String ,Object> headMap = new HashMap<String,Object >();
        headMap.put("reqServCd",StringUtil.trimObject(map.get("/root/MsgHeader/MsgTp")));
        headMap.put("initrSeqno",StringUtil.trimObject(map.get("/root/MsgHeader/CorrId")));
        headMap.put("sndAppCd",StringUtil.trimObject(map.get("/root/MsgHeader/SndSysId")));
        headMap.put("servInitrBrch",StringUtil.trimObject(map.get("/root/MsgHeader/SndBankId")));
        Map<String ,Object> bodyMap = new HashMap<String,Object >();
        bodyMap.put("BizMsg",nginxMsg);
        nginxMap.put("head",headMap);
        nginxMap.put("body",bodyMap);
        JSONObject nginxMapObject = new JSONObject(nginxMap);
        String nginxUrl = StringUtil.trimObject(map.get("NginxUrl"));
        String busUrl = StringUtil.trimObject(map.get("/root/MsgHeader/ClbckUrl"));

        JSONObject busMapObject = null;
        if(StringUtils.isNotBlank(busMsg)){
            Map<String ,Object> busMap = new HashMap<String,Object >();
            Map<String ,Object> bodyBusMap = new HashMap<String,Object >();
            busMap.put("head",headMap);
            bodyBusMap.put("BizMsg",busMsg);
            busMap.put("body",bodyBusMap);
            busMapObject = new JSONObject(busMap);
            responseSend( nginxMapObject.toJSONString(),nginxUrl,busMapObject.toJSONString(), busUrl,null);
        }else{
            responseSend(nginxMapObject.toJSONString(),nginxUrl,busUrl);

        }



    }

    /**
     * 主动发送报文至ngixn服务器|业务系统
     * @param bizMsg
     * @param nginxUrl
     * @param busUrl
     */
    public static  void responseSend(String bizMsg,String nginxUrl,String busUrl) {
        responseSend( bizMsg,nginxUrl,null, busUrl,null);
    }
    /**
     * 主动发送报文至ngixn服务器|业务系统
     * @param nginxMsg
     * @param nginxUrl
     * @param busMsg
     * @param busUrl
     * @param requestHeaders
     */
    public static  void responseSend(String nginxMsg,String nginxUrl,String busMsg,String busUrl,HttpHeaders requestHeaders){
        //定义http请求对象
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        if(requestHeaders == null){
            requestHeaders = new HttpHeaders();
        }
        //定义http Head头
        requestHeaders.add("Content-Type", "application/json");
        requestHeaders.add("Accept-Language", "zh-CN,zh;q=0.9");
        //定义请求数据信息
        LOGGER.info("http客户端发送nginx数据:"+nginxMsg);
        HttpEntity<String> requestEntity = new HttpEntity<String>(nginxMsg, requestHeaders);
        //先将http请求发往nginx,如果失败发往业务系统
        LOGGER.info("http客户端发送nginxUrl:[{}]",nginxUrl);
        ResponseEntity<String> response=template.postForEntity(nginxUrl, requestEntity, String.class);
        String respJson = response.getBody();
        if(response.getStatusCodeValue() == 200){
            LOGGER.info("http发往nginx,响应数据[{}]",respJson);
//            Map<String,Object> rspMap = JSON.parseObjecteObject(respJson);
        }else{
            LOGGER.info("http发往nginx状态[{}],响应数据[{}]：",response.getStatusCodeValue(),respJson);
            //http请求发往业务系统
            LOGGER.info("http客户端业务系统发送busUrl:[{}]",busUrl);
            if(StringUtils.isNotBlank(busMsg)){
                //如果需要变更报文
                requestEntity = new HttpEntity<String>(busMsg, requestHeaders);
            }
            response=template.postForEntity(busUrl, requestEntity, String.class);
            String respBusJson = response.getBody();
            LOGGER.info("http请求业务系统状态[{}],响应数据[{}]" ,response.getStatusCodeValue(), respBusJson);
        }

    }

    /**
     * http业务发送(单方向)
     * @param bizMsg
     * @param url
     * @param requestHeaders
     */
    public static  void responseSend(String bizMsg,String url,HttpHeaders requestHeaders){
        //定义http请求对象
        RestTemplate template = new RestTemplate();
        template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
        if(requestHeaders == null){
            requestHeaders = new HttpHeaders();
        }
        //定义http Head头
        requestHeaders.add("Content-Type", "application/json");
        requestHeaders.add("Accept-Language", "zh-CN,zh;q=0.9");
        //定义请求数据信息
        LOGGER.info("http客户端发送发送数据:"+bizMsg);
        HttpEntity<String> requestEntity = new HttpEntity<String>(bizMsg, requestHeaders);
        //先将http请求发往nginx,如果失败发往业务系统
        LOGGER.info("http客户端发送url:[{}]",url);
        ResponseEntity<String> response=template.postForEntity(url, requestEntity, String.class);
        LOGGER.info("http请求业务系统状态[{}]" ,response.getStatusCodeValue());
        if(response.getStatusCodeValue() == 200){
            LOGGER.info("http请求响应数据成功");
//            LOGGER.info("http发往nginx,响应数据[{}]",respJson);
//            Map<String,Object> rspMap = JSON.parseObject(respJson);
        }else{
            String respJson = response.getBody();
            LOGGER.error("http请求响应数据[{}]",respJson);
        }

    }
}
